package com.glodon.paas.activity.biz;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.glodon.paas.util.ObjectUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

@Component("accountClient")
public class AccountClient {

    private static Logger logger        = LoggerFactory.getLogger(AccountClient.class);

    @Value("${api.internal.account.url}")
    private String        accountApiUrl = "http://127.0.0.1:8080/account/api/internal";

    /**
     * 获取联系人ID列表 http://127.0.0.1:8080/account/api/internal/communicateBook/contactId /{userId}
     * 
     * @param userId
     * @return
     */
    public List<String> contactId(String userId) {
        List<String> temp = new ArrayList<String>();
        try {
            // rest参数
            ClientResponse client = createResource().path("communicateBook/contactId/" + userId).type(APPLICATION_JSON_TYPE).get(ClientResponse.class);

            if (client.getStatus() == 204) {
                // 成功，返回值是null
                return temp;
            } else if (client.getStatus() == 200) {
                String str = client.getEntity(String.class);
                temp = JSON.parseArray(str, String.class);
                return temp;
            } else {
                logger.error(" error:");
                return temp;
            }
        } catch (Exception e) {
            logger.error(" error:" + e.getMessage(), e);

        }
        return temp;
    }

    static WebResource webResource;

    private WebResource createResource() {
        if (webResource == null) {
            ClientConfig config = new DefaultClientConfig();
            Client client = Client.create(config);
            webResource = client.resource(accountApiUrl);
        }
        return webResource;
    }

    public static void main(String[] args) {
        AccountClient client = new AccountClient();
        List<String> list = client.contactId("hc");

        System.out.println(ObjectUtil.toJson(list));
    }
}
